package com.spring.arch.uaa.oauth2.encoder;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.codec.Hex;

import java.security.MessageDigest;

/**
 * 登录密码加密
 *
 * @author: zhangLin
 * @date: 2019-08-27 16:28
 */
@Slf4j
public class LoginMd5
{

    public static void main(String[] args) {
        try {
            System.out.println(encodePassword("12345678", "948317"));
//            System.out.println(encodePassword("1qazxsw2", "912304"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String encodePassword(String password, String salt) {
        if (StringUtils.isBlank(password) || StringUtils.isBlank(salt)) {
            return null;
        }

        byte[] saltBytes = salt.getBytes();
        byte[] sourceBytes = password.getBytes();

        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.reset();
            digest.update(saltBytes);
            byte[] hashed = digest.digest(sourceBytes);

            digest.reset();
            hashed = digest.digest(hashed);

            return new String(Hex.encode(hashed));

        }
        catch (Exception e) {
            log.info(e.toString());
            return null;
        }
    }
}
